import gtk
import sys, os, shutil, stat
import time, datetime
from engine import Widgets
from lib import filesmime as mimetypes
from abcommon import *

class treeView(Widgets):
	_instance = None
	
	def __init__(self):
		Widgets.__init__(self)
		
		self.widget = self.XMLtree.getWidget("LocalTree")
		self.__columns = {
			"header": gtk.ListStore(str, str, str, str, str),
			"type"	: gtk.TreeViewColumn("-", gtk.CellRendererText(), text = 0),
			"icon"	: gtk.TreeViewColumn("#", gtk.CellRendererPixbuf(), icon_name = 1),
			"title"	: gtk.TreeViewColumn("Filename", gtk.CellRendererText(), text = 2),
			"size"	: gtk.TreeViewColumn("Size", gtk.CellRendererText(), text = 3),
			"mtime"	: gtk.TreeViewColumn("Last Edit", gtk.CellRendererText(), text = 4),
		}
		self.__mimetype = (os.path.isfile('/usr/bin/gnome-session') \
					   and mimetypes.Gnome()) \
					   or mimetypes.notGnome(24)
		
	def _headerSet(self, widget, visible):
		self.widget.set_headers_visible(visible)
		self.widget.set_model(self.__columns[widget])
		
	def _columnSet(self, widget, visible, resizable, id):
		self.__columns[widget].set_visible(visible)
		self.__columns[widget].set_resizable(resizable)
		self.__columns[widget].set_sort_column_id(id)
		self.widget.append_column(self.__columns[widget])
		
	def clearRows(self):
		self.__columns["header"].clear()

	def listFiles(self, defaultPath = ".", showHidden = 0):
		try:
			files = {
				"local": os.listdir(defaultPath),
				"tree" : [("directory", self.__mimetype.return_folder_mime(), ".." , "4096", "")]
			}
		except: return None
			
		for item in files["local"]:
			if showHidden == 0 and item[0] == ".": continue
			try: stats = os.stat(os.path.join(".", item))
			except: continue
				
			file = {
				"type": os.path.isdir(item) and "directory" or "file", 
				"mime": os.path.isdir(item) \
						and self.__mimetype.return_folder_mime() \
						or self.__mimetype.return_mime(item), 
				"name": item,
				"size": str(stats.st_size),
				"edit": str(datetime.datetime.fromtimestamp(stats.st_mtime))
			}	
			files["tree"].append((
				file["type"], file["mime"], file["name"], file["size"], file["edit"]))
		files["tree"].sort()
		
		return files["tree"]
			
	def loadRows(self):
		self.clearRows()
		for file in self.listFiles():
			self.__columns["header"].append([
				file[0], file[1], file[2], file[3], file[4]])
			
class treeViewEngine(treeView):
	
	def __init__(self):
		treeView.__init__(self)
		
	def pwd(self):
		return os.getcwd()
	
	def cwd(self, name):
		if name == "~":
			name = os.path.expanduser("~%s" % os.environ['USER'])
		os.chdir(name)
		
	def delete(self, name):
		os.remove(name)
		
	def rmdir(self, name):
		shutil.rmtree(name)
	
class treeViewPath(Widgets):

	def __init__(self):
		Widgets.__init__(self)
		
		self.widget = self.XMLtree.getWidget("LocalPathText")
		self.treeView = Invoker(treeViewEngine)
		self.updatePath(self.treeView.pwd())
		
	def updatePath(self, path):
		self.widget.set_text(path)
		
	def getText(self): 
		return self.widget.get_text()
	
#class treeViewEvents(treeViewEngine):
	
	#def __init__(self):
		#treeViewEngine.__init__(self)
		#print Invoker(treeViewEngine, self)
		
		#self._treeViewPath = treeViewPath()	

class UI(treeViewEngine):
	
	def __init__(self):
		treeViewEngine.__init__(self)
		self.treeViewPath = treeViewPath()
		
		self._headerSet("header", True)
		self._columnSet("type", False, False, -1)
		self._columnSet("icon", True, False, 0)
		self._columnSet("title", True, True, 1)
		self._columnSet("size", True, True, 2)
		self._columnSet("mtime", True, True, 3)
		self.loadRows()
		self.connectEvents()
		
	def onPathChange(self, *args):
		self.cwd(self.treeViewPath.getText())
		self.clearRows()
		self.loadRows()
		
		LogView = Invoker(Widgets.selectWidget("LogView").UI)
		LogView.write("Directory corrente: %s" % self.pwd())
		
	def onRowClick(self, *args):
		model, iter = self.widget.get_selection().get_selected()
		file = {
			"type": model.get_value(iter, 0),
			"name": model.get_value(iter, 2)
		}
		
		if file["type"] == "directory":
			self.cwd(os.path.join(self.pwd(), file["name"]))
			self.loadRows()
			self.treeViewPath.updatePath(self.pwd())
		else:
			try:
				open = os.system("xdg-open '", name, "'")
			except Exception, e:
				print e

		LogView = Invoker(Widgets.selectWidget("LogView").UI)
		LogView.write("Directory corrente: %s" % self.pwd())

	def connectEvents(self):
		self.XMLtree.connectSignals({
			"on_LocalTree_row_clicked" : self.onRowClick,
			"on_LocalPathText_activate": self.onPathChange,
		})